package com.newshub.business.controller;

import com.newshub.common.Result;
import com.newshub.business.dto.CategoryQueryDTO;
import com.newshub.business.dto.PageResult;
import com.newshub.business.entity.Category;
import com.newshub.business.service.CategoryService;
import com.newshub.logging.annotation.BusinessLog;
import com.newshub.logging.annotation.LogLevel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 分类管理控制器
 */
@RestController
@RequestMapping("/api/category")
@CrossOrigin(origins = "*")
public class CategoryController {
    
    @Autowired
    private CategoryService categoryService;
    
    /**
     * 分页查询分类
     */
    @PostMapping("/page")
    @BusinessLog(level = LogLevel.INFO, description = "分页查询分类")
    public Result<PageResult<Category>> getCategoryPage(@RequestBody CategoryQueryDTO queryDTO) {
        try {
            PageResult<Category> result = categoryService.getCategoryPage(queryDTO);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("查询分类失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取所有分类
     */
    @GetMapping("/list")
    @BusinessLog(level = LogLevel.INFO, description = "获取所有分类")
    public Result<List<Category>> getAllCategories() {
        try {
            List<Category> categories = categoryService.getAllCategories();
            return Result.success(categories);
        } catch (Exception e) {
            return Result.error("获取分类列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据ID获取分类
     */
    @GetMapping("/{id}")
    @BusinessLog(level = LogLevel.INFO, description = "根据ID获取分类")
    public Result<Category> getCategoryById(@PathVariable Integer id) {
        try {
            Category category = categoryService.getCategoryById(id);
            if (category != null) {
                return Result.success(category);
            } else {
                return Result.error("分类不存在");
            }
        } catch (Exception e) {
            return Result.error("获取分类失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据名称获取分类
     */
    @GetMapping("/name/{name}")
    @BusinessLog(level = LogLevel.INFO, description = "根据名称获取分类")
    public Result<Category> getCategoryByName(@PathVariable String name) {
        try {
            Category category = categoryService.getCategoryByName(name);
            if (category != null) {
                return Result.success(category);
            } else {
                return Result.error("分类不存在");
            }
        } catch (Exception e) {
            return Result.error("获取分类失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据名称获取分类
     */
    @GetMapping("/code/{code}")
    @BusinessLog(level = LogLevel.INFO, description = "根据编码获取分类")
    public Result<Category> getCategoryByCode(@PathVariable String code) {
        try {
            Category category = categoryService.getCategoryByCode(code);
            if (category != null) {
                return Result.success(category);
            } else {
                return Result.error("分类不存在");
            }
        } catch (Exception e) {
            return Result.error("获取分类失败: " + e.getMessage());
        }
    }
    
    /**
     * 添加分类
     */
    @PostMapping
    @BusinessLog(level = LogLevel.INFO, description = "添加分类")
    public Result<String> addCategory(@RequestBody Category category) {
        try {
            // 检查名称是否重复
            Category existingCategory = categoryService.getCategoryByName(category.getName());
            if (existingCategory != null) {
                return Result.error("分类名称已存在");
            }
            
            // 检查编码是否重复
            existingCategory = categoryService.getCategoryByCode(category.getCode());
            if (existingCategory != null) {
                return Result.error("分类编码已存在");
            }
            
            boolean success = categoryService.addCategory(category);
            if (success) {
                return Result.success("添加分类成功");
            } else {
                return Result.error("添加分类失败");
            }
        } catch (Exception e) {
            return Result.error("添加分类失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新分类
     */
    @PutMapping("/{id}")
    @BusinessLog(level = LogLevel.INFO, description = "更新分类")
    public Result<String> updateCategory(@PathVariable Integer id, @RequestBody Category category) {
        try {
            category.setId(id);
            
            // 检查名称是否重复（排除当前分类）
            Category existingCategory = categoryService.getCategoryByName(category.getName());
            if (existingCategory != null && !existingCategory.getId().equals(id)) {
                return Result.error("分类名称已存在");
            }
            
            // 检查编码是否重复（排除当前分类）
            existingCategory = categoryService.getCategoryByCode(category.getCode());
            if (existingCategory != null && !existingCategory.getId().equals(id)) {
                return Result.error("分类编码已存在");
            }
            
            boolean success = categoryService.updateCategory(category);
            if (success) {
                return Result.success("更新分类成功");
            } else {
                return Result.error("更新分类失败");
            }
        } catch (Exception e) {
            return Result.error("更新分类失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除分类
     */
    @DeleteMapping("/{id}")
    @BusinessLog(level = LogLevel.WARN, description = "删除分类")
    public Result<String> deleteCategory(@PathVariable Integer id) {
        try {
            boolean success = categoryService.deleteCategory(id);
            if (success) {
                return Result.success("删除分类成功");
            } else {
                return Result.error("删除分类失败");
            }
        } catch (Exception e) {
            return Result.error("删除分类失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新分类状态
     */
    @PutMapping("/{id}/status")
    @BusinessLog(level = LogLevel.INFO, description = "更新分类状态")
    public Result<String> updateCategoryStatus(@PathVariable Integer id, @RequestParam Integer status) {
        try {
            boolean success = categoryService.updateCategoryStatus(id, status);
            if (success) {
                return Result.success("更新分类状态成功");
            } else {
                return Result.error("更新分类状态失败");
            }
        } catch (Exception e) {
            return Result.error("更新分类状态失败: " + e.getMessage());
        }
    }
    
    /**
     * 批量删除分类
     */
    @DeleteMapping("/batch")
    @BusinessLog(level = LogLevel.WARN, description = "批量删除分类")
    public Result<String> batchDeleteCategories(@RequestBody List<Integer> ids) {
        try {
            boolean success = categoryService.batchDeleteCategories(ids);
            if (success) {
                return Result.success("批量删除分类成功");
            } else {
                return Result.error("批量删除分类失败");
            }
        } catch (Exception e) {
            return Result.error("批量删除分类失败: " + e.getMessage());
        }
    }
}

